﻿using System;
using BoldBrick.Core.Logging;
using BoldBrick.OneIntranet.HR.Resources;
using BoldBrick.OneIntranet.HR.Utils;
using BoldBrick.SharePoint.CommonControls.Layouts;
using Microsoft.SharePoint;
using BoldBrick.SharePoint.CommonControls.Extensions;

namespace BoldBrick.OneIntranet.HR.Layouts
{
	public partial class CopyPositionPage : BaseDialogPage
	{
		private static readonly ILogger log = Logger.GetLogger(typeof(CopyPositionPage));

		#region ------ BaseDialogPage Members -----------------------------------------------------

		protected override string GetDescription(uint language)
		{
			this.DialogIconType = DialogIconTypes.Question;

			SPListItem item = GetListItem(language);
			if (item == null)
				return null;

			string description = ResourceBuilder.GetResource("CopyPositionPage_Description", language, item.Title);
			return description;
		}

		protected override string GetCancelButtonText(uint language)
		{
			return ResourceBuilder.GetResource("CopyPositionPage_CancelButton_Text", language);
		}

		protected override string GetOKButtonText(uint language)
		{
			return ResourceBuilder.GetResource("CopyPositionPage_OkButton_Text", language);
		}

		protected override string GetTitle(uint language)
		{
			return ResourceBuilder.GetResource("CopyPositionPage_Title", language);
		}

		#endregion

		#region ------ Action Methods -------------------------------------------------------------

		protected override bool DoAction(out string errorMessage)
		{
			errorMessage = null;

			uint language = SPContext.Current.Web.Language;
			SPListItem item = GetListItem(language);
			if (item == null)
				return false;

			int? itemIDNew;
			try
			{
				itemIDNew = PositionsHelper.CopyPosition(item);
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Error, ex, "'PositionsHelper.CopyPosition' method failed.");
				errorMessage = ex.Message;
				return false;
			}

			if (!itemIDNew.HasValue)
			{
				log.Write(LogLevel.Error, "Error during position copy: new item ID is null");
				errorMessage = ResourceBuilder.GetResource("CopyPositionPage_Error_NoNewItemID", language);
				return false;
			}

			string listItemUrl = item.ParentList.GetListItemUrl(PAGETYPE.PAGE_EDITFORM, itemIDNew.Value);
			Redirect(listItemUrl, true);

			return true;
		}
		
		#endregion
	}
}
